<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script src="../resources/common.js"></script>
<script src="../resources/picker-common.js"></script>
<script src="../calendar-picker/resources/calendar-picker-common.js"></script>
</head>
<body>
<input type="week" id="week0" min="2019-W04" max="2019-W20">
<input type="week" id="week1" min="5000-W04" max="5000-W20">
<input type="week" id="week2" >
<input type="week" id="week3" min="2019-W04" max="2019-W20" step="3" value="2019-W08">
<script>

promise_test(() => {
  let weekElement = document.getElementById("week0");
  return openPickerWithPromise(weekElement)
  .then(() => {
    eventSender.keyDown('Enter');
    assert_equals(internals.pagePopupWindow, null, "Enter key should dismiss popup.");

    assert_equals(weekElement.value, "2019-W20", "Week should be selected if user hits enter without other input");
  });
}, "Week picker: Picker should default to the day closest to max when it comes before the current date");

promise_test(() => {
  let weekElement = document.getElementById("week1");
  return openPickerWithPromise(weekElement)
  .then(() => {
    eventSender.keyDown('Enter');
    assert_equals(internals.pagePopupWindow, null, "Enter key should dismiss popup.");

    // Note: test will need to be updated in the year 5000 :)
    assert_equals(weekElement.value, "5000-W04", "Week should be selected if user hits enter without other input");
  });
}, "Week picker: Picker should default to the day closest to min when it comes after the current date");

promise_test(() => {
  let weekElement = document.getElementById("week2");
  return openPickerWithPromise(weekElement)
  .then(() => {
    eventSender.keyDown('Enter');
    assert_equals(internals.pagePopupWindow, null, "Enter key should dismiss popup.");
    let weekExpr = new RegExp(`${new Date().getFullYear()}-W\\d{2}`);

    assert_true(weekExpr.test(weekElement.value), "Week control should default to current week");
  });
}, "Week picker: Picker should default the current week if it is valid");

promise_test(() => {
  let weekElement = document.getElementById("week3");
  return openPickerWithPromise(weekElement)
  .then(() => {
    eventSender.keyDown('Enter');
    assert_equals(internals.pagePopupWindow, null, "Enter key should dismiss popup.");

    assert_equals(weekElement.value, "2019-W10", "Valid week closest to starting value should be selected if user hits enter without other input");
  });
}, "Week picker: If the input's initial value is invalid due to step attribute, should select the nearest valid week");

</script>
</body>
</html>
